package com.example.webcrawler.controller;

import com.example.webcrawler.model.DebugSession;
import com.example.webcrawler.service.mpl.DebugService;
import com.example.webcrawler.service.mpl.WebAnalysisService;
import com.google.gson.JsonObject;
import com.microsoft.playwright.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/debug")
public class DebugController {
    private static final Logger logger = LoggerFactory.getLogger(DebugController.class);

    @Autowired
    private DebugService debugService;

    @Autowired

    private WebAnalysisService webAnalysisService;

    /**
     * 创建调试会话
     */
    @PostMapping("/session")
    public ResponseEntity<Map<String, String>> createDebugSession(@RequestParam String pageId) {
        // 根据pageId获取对应的Page对象
        Page page = webAnalysisService.getPageById(pageId);

        if (page == null) {
            return ResponseEntity.status(404).body(Map.of("error", "Page not found for id: " + pageId));
        }

        // 创建真实的调试会话
        String sessionId = debugService.createDebugSession(page);

        if (sessionId != null) {
            return ResponseEntity.ok(Map.of("sessionId", sessionId, "status", "success"));
        } else {
            return ResponseEntity.status(500).body(Map.of("error", "Failed to create debug session"));
        }
    }


    /**
     * 设置JavaScript断点
     */
    @PostMapping("/{sessionId}/breakpoints/javascript")
    public ResponseEntity<Map<String, Object>> setJavaScriptBreakpoint(
            @PathVariable String sessionId,
            @RequestBody Map<String, Object> breakpointInfo) {

        String url = (String) breakpointInfo.get("url");
        int lineNumber = ((Number) breakpointInfo.get("lineNumber")).intValue();
        int columnNumber = ((Number) breakpointInfo.get("columnNumber")).intValue();
        String condition = (String) breakpointInfo.get("condition");

        boolean success = debugService.setJavaScriptBreakpoint(sessionId, url, lineNumber, columnNumber, condition);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 设置请求断点
     */
    @PostMapping("/{sessionId}/breakpoints/request")
    public ResponseEntity<Map<String, Object>> setRequestBreakpoint(
            @PathVariable String sessionId,
            @RequestBody Map<String, String> breakpointInfo) {

        String urlPattern = breakpointInfo.get("urlPattern");
        boolean success = debugService.setRequestBreakpoint(sessionId, urlPattern);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 设置DOM断点
     */
    @PostMapping("/{sessionId}/breakpoints/dom")
    public ResponseEntity<Map<String, Object>> setDOMBreakpoint(
            @PathVariable String sessionId,
            @RequestBody Map<String, Object> breakpointInfo) {

        int nodeId = ((Number) breakpointInfo.get("nodeId")).intValue();
        String type = (String) breakpointInfo.get("type");
        boolean success = debugService.setDOMBreakpoint(sessionId, nodeId, type);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 设置异常断点
     */
    @PostMapping("/{sessionId}/breakpoints/exception")
    public ResponseEntity<Map<String, Object>> setExceptionBreakpoint(
            @PathVariable String sessionId,
            @RequestBody Map<String, String> breakpointInfo) {

        String type = breakpointInfo.get("type");
        boolean success = debugService.setExceptionBreakpoint(sessionId, type);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 移除断点
     */
    @DeleteMapping("/{sessionId}/breakpoints/{breakpointId}")
    public ResponseEntity<Map<String, Object>> removeBreakpoint(
            @PathVariable String sessionId,
            @PathVariable String breakpointId) {

        boolean success = debugService.removeBreakpoint(sessionId, breakpointId);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 启用断点
     */
    @PostMapping("/{sessionId}/breakpoints/{breakpointId}/enable")
    public ResponseEntity<Map<String, Object>> enableBreakpoint(
            @PathVariable String sessionId,
            @PathVariable String breakpointId) {

        boolean success = debugService.enableBreakpoint(sessionId, breakpointId);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 禁用断点
     */
    @PostMapping("/{sessionId}/breakpoints/{breakpointId}/disable")
    public ResponseEntity<Map<String, Object>> disableBreakpoint(
            @PathVariable String sessionId,
            @PathVariable String breakpointId) {

        boolean success = debugService.disableBreakpoint(sessionId, breakpointId);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 获取所有断点
     */
    @GetMapping("/{sessionId}/breakpoints")
    public ResponseEntity<List<com.example.webcrawler.model.Breakpoint>> getBreakpoints(
            @PathVariable String sessionId) {

        List<com.example.webcrawler.model.Breakpoint> breakpoints = debugService.getBreakpoints(sessionId);
        return ResponseEntity.ok(breakpoints);
    }

    /**
     * 恢复执行
     */
    @PostMapping("/{sessionId}/resume")
    public ResponseEntity<Map<String, Object>> resume(@PathVariable String sessionId) {
        boolean success = debugService.resume(sessionId);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 单步执行
     */
    @PostMapping("/{sessionId}/step-over")
    public ResponseEntity<Map<String, Object>> stepOver(@PathVariable String sessionId) {
        boolean success = debugService.stepOver(sessionId);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 进入函数
     */
    @PostMapping("/{sessionId}/step-into")
    public ResponseEntity<Map<String, Object>> stepInto(@PathVariable String sessionId) {
        boolean success = debugService.stepInto(sessionId);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 跳出函数
     */
    @PostMapping("/{sessionId}/step-out")
    public ResponseEntity<Map<String, Object>> stepOut(@PathVariable String sessionId) {
        boolean success = debugService.stepOut(sessionId);
        return ResponseEntity.ok(Map.of("success", success));
    }

    /**
     * 获取变量信息
     */
    @GetMapping("/{sessionId}/variables")
    public ResponseEntity<JsonObject> getVariables(
            @PathVariable String sessionId,
            @RequestParam(required = false) String callFrameId) {
        JsonObject variables = debugService.getVariables(sessionId, callFrameId);
        return ResponseEntity.ok(variables);
    }

    /**
     * 获取调用栈信息
     */
    @GetMapping("/{sessionId}/callstack")
    public ResponseEntity<List<String>> getCallStack(@PathVariable String sessionId) {
        List<String> callStack = debugService.getCallStack(sessionId);
        return ResponseEntity.ok(callStack);
    }

    /**
     * 获取调试会话状态
     */
    @GetMapping("/{sessionId}/status")
    public ResponseEntity<DebugSession> getDebugStatus(@PathVariable String sessionId) {
        DebugSession session = debugService.getDebugSession(sessionId);
        if (session != null) {
            return ResponseEntity.ok(session);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 断开调试会话
     */
    @DeleteMapping("/{sessionId}")
    public ResponseEntity<Map<String, Object>> detachSession(@PathVariable String sessionId) {
        boolean success = debugService.detachSession(sessionId);
        return ResponseEntity.ok(Map.of("success", success));
    }
}
